package com.lzgang.ctrl.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

@RestController
public class CtrlController {

    @Value("${shell-path}")
    private String shellPath;

    @Value("${file-path}")
    private String imagePath;

    /**
     * 执行shell命令/脚本
     *
     * @param cmdScript
     * @param batPath
     * @return
     */
    @GetMapping("batCtrl")
    public String batCtrl(@RequestParam String cmdScript, @RequestParam(required = false) String batPath) {
        if (!StringUtils.hasText(batPath)) batPath = shellPath;
        /** 如果目录下有此脚本，执行脚本，否则作为一个命令执行 */
        return callCmd(new File(batPath + cmdScript).exists() ? batPath + cmdScript : cmdScript);
    }

    @GetMapping("batCtrl1")
    public String batCtrl1(@RequestParam String cmdScript, @RequestParam(required = false) String batPath) {
        if (!StringUtils.hasText(batPath)) batPath = shellPath;
        try {
            Process child = Runtime.getRuntime().exec(new File(batPath + cmdScript).exists() ? batPath + cmdScript : cmdScript);
            System.out.println("callCmd execute finished");
            return "deploying, please wait a few minutes";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFiles(@RequestParam("file") MultipartFile file) throws Exception {
        if (Objects.isNull(file) || file.isEmpty()) throw new RuntimeException("文件不存在");
        String filePath = imagePath + file.getOriginalFilename();
        File dest = new File(filePath);
        /** 如果文件夹不存在，创建文件夹 */
        if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs();
        file.transferTo(dest);
        String fix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (!".zip".equals(fix)) throw new RuntimeException("只接受zip压缩包");
        return this.callCmd(shellPath + "rebuild.sh " + file.getOriginalFilename().replace(fix, ""));
    }

    /**
     * 执行shell命令/脚本
     *
     * @param locationCmd
     * @return
     */
    private String callCmd(String locationCmd) {
        StringBuilder sb = new StringBuilder();
        try {
            Process child = Runtime.getRuntime().exec(locationCmd);
            InputStream in = child.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "gbk"));
            String line;
            while ((line = bufferedReader.readLine()) != null) sb.append(line + "\n");
            in.close();
            child.waitFor();
            System.out.println("callCmd execute finished");
            return sb.toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

}
